import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/empty_widget.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/components/refresh_footer.dart';
import 'package:kxy_flutter_app/components/refresh_header.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/course_complete_info.dart';
import 'package:kxy_flutter_app/view/course/completed_item_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CompletedListView extends StatefulWidget {
  final String courseId;
  CompletedListView({Key key, @required this.courseId}) : super(key: key);

  @override
  _CompletedListViewState createState() => _CompletedListViewState();
}

class _CompletedListViewState extends State<CompletedListView> {
  int page = 1;
  int totalCount = 0;
  Future loadFuture;
  List<CourseCompleteInfo> infoList = new List<CourseCompleteInfo>();
  RefreshController controller = new RefreshController();
  TextEditingController searchTextCtrl = new TextEditingController();

  @override
  void initState() {
    super.initState();
    loadFuture = reload();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: searchField()),
      body: FutureBuilder(
        future: loadFuture,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return body();
          }
          return LoadingWidget();
        },
      ),
    );
  }

  Widget body() {
    return SmartRefresher(
      controller: controller,
      enablePullDown: true,
      enablePullUp: true,
      header: RefreshHeader(),
      footer: RefreshFooter(),
      child: infoListWidget(),
      onLoading: () async {
        if (infoList.length < totalCount) {
          await loadMore();
          controller.loadComplete();
        } else {
          controller.loadNoData();
        }
      },
      onRefresh: () async {
        await reload();
        controller.refreshCompleted();
      },
    );
  }

  Widget infoListWidget() {
    if (infoList.length == 0) {
      return EmptyWidget(onRefresh: reload);
    }

    return ListView.builder(
      itemBuilder: (cxt, index) {
        return CompletedItemWidget(
          info: infoList[index],
          index: index,
        );
      },
      itemCount: infoList.length,
    );
  }

  Widget searchField() {
    return ConstrainedBox(
      constraints: BoxConstraints(
        maxHeight: 32,
        maxWidth: 300,
      ),
      child: TextField(
        onEditingComplete: () {
          FocusScope.of(context).requestFocus(new FocusNode());
          reload();
        },
        controller: searchTextCtrl,
        decoration: InputDecoration(
          filled: true,
          hintText: '请输入搜索内容',
          contentPadding: const EdgeInsets.symmetric(vertical: 0),
          prefixIcon: Icon(
            Icons.search,
            color: Colors.black54,
            size: 16,
          ),
          fillColor: Color.fromRGBO(240, 240, 240, 1),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(5),
            borderSide: BorderSide.none,
          ),
        ),
      ),
    );
  }

  Future reload() async {
    page = 1;
    totalCount = 0;
    infoList.clear();
    await loadMore();
  }

  Future loadMore() async {
    var res = await Http.instance.post('/train-app/courseapp/allUserCourseStatus', params: {
      'userId': Auth.instance.userId,
      'courseId': widget.courseId,
      'page': page,
      'limit': 50,
      'realname': searchTextCtrl.text,
    });

    if (res.code == 200) {
      setState(() {
        totalCount = res.data['totalCount'];
        (res.data['list'] as List).forEach((element) {
          var info = CourseCompleteInfo.fromJson(element);
          infoList.add(info);
        });
        page++;
      });
    } else {
      Fluttertoast.showToast(msg: res.msg);
    }
  }
}
